/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ngramassigment.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import ngramassigment.Config;

/**
 *
 * @author Tran
 */
public class DatabaseFunction {

    private static DatabaseFunction instance = null;

    public static DatabaseFunction getInstance() {
        if (instance == null) {
            instance = new DatabaseFunction();
        }
        return instance;
    }

    public DatabaseFunction() {
    }

    public Connection connectDatabase() {
        Connection connection = null;
        try {
            Class.forName("org.sqlite.JDBC");
            connection = DriverManager.getConnection("jdbc:" + Config.DATABASE_TYPE + ":" + Config.DATABASE_NAME);
        } catch (ClassNotFoundException | SQLException e) {
            return null;
        }
        return connection;
    }

    public boolean closeDatabase(Connection connection) {
        try {
            connection.close();
        } catch (SQLException ex) {
            return false;
        }
        return true;
    }

//    public Connection getConnection() {
//        if (connection == null) {
//            connectDatabase();
//        }
//        return connection;
//    }
    public boolean executeCreate(String sql, Connection con) {
        Statement stmt = null;
        try {
            stmt = con.createStatement();
            stmt.executeUpdate(sql);
            stmt.close();
        } catch (SQLException ex) {
            return false;
        }
        return true;
    }

    public boolean executeInsertUpdateDelete(String sql, Connection con) {
        Statement stmt = null;

        try {
            stmt = con.createStatement();
            stmt.executeUpdate(sql);
            stmt.close();            
        } catch (SQLException ex) {
            return false;
        }
        return true;
    }

//    public ResultSet executeSelect(String sql, Connection con) throws SQLException {
//        PreparedStatement stmt = null;
//        ResultSet rs = null;
//
//        stmt = con.prepareStatement(sql);
//        rs = stmt.executeQuery();
//        stmt.close();
//        return rs;
//    }
}
